package com.tripshare.sdk.weixin.api.util;

import com.alibaba.druid.support.json.JSONUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Slf4j
public class AccessTokenUtil {

    private static RestTemplate restTemplate = new RestTemplate();

    private static String accessToken;

    public static String refreshAccessToken(String appid, String secret) {
        Map map = restTemplate.getForObject("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}", Map.class, appid, secret);
        log.info("refreshAccessToken appId={} secret={} result={}", appid, secret, JSONUtils.toJSONString(map));
        String tmpAccessToken = (String) map.get("access_token");
        accessToken = tmpAccessToken;
        return tmpAccessToken;
    }

    public static String getAccessToken() {
        if (StringUtils.isBlank(accessToken)) {
            throw new RuntimeException("accessToken is empty");
        }
        return accessToken;
    }
}
